package com.zyw.zhuangdian.controller;

import com.alibaba.fastjson.JSONObject;
import com.zyw.zhuangdian.pojo.Resp;
import com.zyw.zhuangdian.pojo.in.ConstantDtoIn;
import com.zyw.zhuangdian.pojo.out.ConstantDtoOut;
import com.zyw.zhuangdian.service.ConstantService;
import com.zyw.zhuangdian.util.Assert;
import com.zyw.zhuangdian.util.BeanConvertUtil;
import com.zyw.zhuangdian.util.RespUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/constant")
@RequiredArgsConstructor
@Slf4j
public class ConstantController {
    private final ConstantService ConstantService;

    /**
     * 增加常量项
     * @param json
     * @return
     */
    @RequestMapping(value = "addConstant",method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> addConstant(@RequestBody JSONObject json){
        Assert.hasKeyAndValue(json,"key","键不能为空");
        Assert.hasKeyAndValue(json,"value","值不能为空");

        ConstantDtoIn in = BeanConvertUtil.covertBean(json, ConstantDtoIn.class);
        Resp<Void> resp = ConstantService.addConstant(in);
        return RespUtil.OK(resp);
    }

    /**
     * 修改常量项
     * @param json
     * @return
     */
    @RequestMapping(value = "updateConstant",method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> updateConstant(@RequestBody JSONObject json){
        Assert.hasKeyAndValue(json,"key","键不能为空");
        Assert.hasKeyAndValue(json,"keyName","键注释不能为空");

        ConstantDtoIn in = BeanConvertUtil.covertBean(json, ConstantDtoIn.class);
        Resp<Void> resp = ConstantService.updateConstant(in);
        return RespUtil.OK(resp);
    }

    /**
     * 删除常量项
     * @param json
     * @return
     */
    @RequestMapping(value = "deleteConstant",method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> deleteConstant(@RequestBody JSONObject json){

        ConstantDtoIn in = BeanConvertUtil.covertBean(json, ConstantDtoIn.class);
        Resp<Void> resp = ConstantService.deleteConstant(in);
        return RespUtil.OK(resp);
    }

    /**
     * 列出常量项
     * @param json (key)
     * @return
     */
    @RequestMapping(value = "listConstant",method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> listConstant(@RequestBody JSONObject json){

        ConstantDtoIn in = BeanConvertUtil.covertBean(json, ConstantDtoIn.class);
        Resp<List<ConstantDtoOut>> resp = ConstantService.listConstants(in);
        return RespUtil.OK(resp);
    }
}
